import {
  VuexModule,
  Module,
  getModule,
  Mutation,
  Action
} from 'vuex-module-decorators'

import router from '@/core/router'
import { userServices, IUserLogin, IProject, IYear } from '@/common/services'
import store from '@/store'
import { _set, _get } from '@/utils/storage'
import md5 from 'js-md5'
import { merge } from 'lodash-es'

// import { asyncRouterMap } from '@/routes'
import { permission } from '@/store/modules/permission'

// 针对不同项目单独处理逻辑
export enum PROJECT_TYPE {
  NORMAL = '一般农户',
  LARGE = '种植大户',
  PLANT = '种粮户'
}

// 各个补贴项目ID
export enum PROJECT_IDS {
  FIRST = '5150_20213',
  SECOND = '5150_20214',
  THIRD = '5150_20215'
}

export interface UserLogin {
  username: string,
  password: string,
  type: number;
  tel?: string
}

export interface IUserState {
  userInfo: IUserInfo
}

export type IUserInfo = IUserLogin['response']

const _default = {
  token: '',
  token2: '',
  usr_id: '',
  usr_nickname: '',
  usr_tel: '',
  usr_sfz: '',
  usr_act: '',
  admin_info: {
    pow_gp_id: '',
    pow_gp_nam: '',
    s_a_id: '',
    s_a_nam: '',
    s_a_nam_all: '',
    task_ids: '',
    work_place: '',
    title1: '',
    title2: '',
    title3: '',
    task_info: [],
    year_info: {}
  }
}

// @todo
// setTimeout(() => {
//   // @ts-ignore
//   permission.SET_PERMISSIONLIST(asyncRouterMap[0].children)
// }, 300)

// dynamic: true, store,
@Module({
  dynamic: true,
  namespaced: true,
  store,
  name: 'user',
  preserveState: sessionStorage.getItem('vuex') !== null,
})
class User extends VuexModule implements IUserState {
  public userInfo: IUserInfo = _default

  // 当前选中项目
  public currentProject: Partial<IProject> = {

  }

  // 当前年份
  public currentYear = 0

  // 项目列表
  public projects: IProject[] = []
  // get projects() {
  //   return this.userInfo ?.admin_info.task_info || []
  // }

  // 可选年份列表
  get years() {
    if (!this.userInfo?.admin_info.year_info) {
      return []
    }
    const years = Object.keys(this.userInfo?.admin_info.year_info).map(item => {
      return {
        label: +item,
        value: this.userInfo?.admin_info.year_info[item]
      }
    })
    return years
  }

  // 一般户
  get isNormal() {
    return this.currentProject.task_usr_tab === PROJECT_TYPE.NORMAL
  }

  // 是否是大户
  get isLarge() {
    return this.currentProject.task_usr_tab === PROJECT_TYPE.LARGE
  }

  // 是否是种植户
  get isPlant() {
    return this.currentProject.task_usr_tab === PROJECT_TYPE.PLANT
  }

  // 是否是第二次补贴
  get isSecondPlant() {
    return this.currentProject.task_id === PROJECT_IDS.SECOND
  }

  // 是否是第三次补贴
  get isThirdPlant() {
    return this.currentProject.task_id === PROJECT_IDS.THIRD
  }

  // 是否具有项目编辑权限
  get hasEditProject() {
    return this.userInfo.admin_info.s_a_id.length <= 6
  }

  // 是否有区县级以上管理权限
  get isThanArea() {
    return this.userInfo.admin_info.s_a_id.length <= 6
  }

  // 是否是市级
  get isProvince() {
    return this.userInfo.admin_info.s_a_id.length === 2
  }

  // 是否有公示生成辖区发放批单
  get hasGenerateOrder() {
    return this.userInfo.admin_info.s_a_id.length === 6
  }

  // 当前用户地区信息
  get currentUserArea() {
    return userModule.userInfo.admin_info
  }

  get isAdmin() {
    return this.userInfo.usr_act === 'admin'
  }

  /**
   * 设置当前选中项目
   *
   * @param {IProject} project
   * @memberof User
   */
  @Mutation
  public SET_CURRENT_PROJECT(project: Partial<IProject>) {
    this.currentProject = Object.assign({}, project);
  }

  /**
   * 设置当前年份
   *
   * @param {number} year
   * @memberof User
   */
  @Mutation
  public SET_CURRENT_YEAR(year: {
    label: number;
    value: IProject[];
  }) {
    this.currentYear = year.label;
    this.projects = year.value;
  }

  // 清空用户信息
  @Mutation
  public CLEAR_USER_INFO() {
    this.userInfo = _default
    // 清空token
    sessionStorage.clear()
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('token2')
    sessionStorage.removeItem('share')
  }

  /**
   * @description 更新用户数据
   *
   * @param {RootStateType} state
   * @param {RootStateType['user']} data 更新的用户数据
   */
  @Mutation
  public UPDATE_USER_INFO(data: IUserInfo) {
    this.userInfo = merge({}, this.userInfo, data)
  }

  // 用户登录 type 1 -> 用户名登录 2->身份证或手机号登录
  @Action
  public async login(data: UserLogin) {
    let { username, password, type, tel }: UserLogin = Object.assign({}, data)
    // // 登录请求参数
    let params: IUserLogin['request'] = {
      // @ts-ignore
      usr_psw: md5(password)
    }
    // 用户名登录
    if (type === 1) {
      params.usr_act = username
    } else {
      // 身份证
      if (tel && tel.length >= 15) {
        params.usr_sfz = tel
      } else {
        // 手机号
        params.usr_tel = tel
      }
    }
    const res = await userServices.login(params)
    // 存储token
    sessionStorage.setItem('token', res.data.token)
    sessionStorage.setItem('token2', res.data.token2)
    // 更新用户信息
    this.UPDATE_USER_INFO(res.data)
    // @ts-ignore
    // permission.SET_PERMISSIONLIST(asyncRouterMap[0].children)
    await permission.getPermissionList()
    
    return res
  }

  @Action
  public getSmsCaptcha({ mobile }: { mobile: number }) {

  }

  // 退出登录
  @Action
  public userLogout() {
    this.CLEAR_USER_INFO()
    this.SET_CURRENT_PROJECT({})
    this.SET_CURRENT_YEAR({
      label: 0,
      value: []
    })
    store.commit('permission/CLEAR_PERMISSION')
    store.commit('area/CLEAR_AREA_DATA')
    router.push('/user/login')
  }
}

export const userModule = getModule(User)

export default User
